<template>
  <el-card>
    <div class="head-container">
      <el-input
        v-model="searchText"
        placeholder="请输入部门名称"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div>
      <el-radio-group v-model="seltype" size="small">
        <el-radio-button label="river">河流</el-radio-button>
        <el-radio-button label="region">行政区划</el-radio-button>
      </el-radio-group>
    </div>
    <div class="head-container">
      <el-tree
        :data="deptOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        show-checkbox
        default-expand-all
        ref="tree"
        node-key="id"
        highlight-current
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
        @check="handleCheck"
      />
    </div>
  </el-card>
</template>

<script>
import { getLakeSegmentTree, getRegionTree } from "@/api/dataResources/common";
import { getRiverSegmentTree } from "@/api/commonApi";
export default {
  name: "TreeSelect",
  data() {
    return {
      searchText: "",
      seltype: "river",
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 存储所有节点ID（用于全选）
      allNodeIds: [],
    };
  },
  watch: {
    searchText(val) {
      this.$refs.tree.filter(val);
    },
    seltype: {
      handler(newVal) {
        if (newVal === "river") {
          this.getRiverTree();
        } else if (newVal === "region") {
          this.getRegionTree();
        }
      },
      immediate: true, // 初始化时执行
    },
    // 监听树形数据变化，数据加载完成后全选
    deptOptions(newVal) {
      if (newVal.length > 0 && this.$refs.tree) {
        this.setAllChecked();
      }
    },
  },
  methods: {
    // 节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 将扁平数据转换为树形结构
    convertToTree(data) {
      const nodeMap = {};
      // 初始化所有节点并收集ID
      this.allNodeIds = []; // 重置ID数组
      data.forEach((node) => {
        this.allNodeIds.push(node.id); // 收集所有节点ID
        nodeMap[node.id] = {
          ...node,
          label: node.name,
          children: [],
        };
      });

      // 构建树形结构
      const tree = [];
      data.forEach((node) => {
        const currentNode = nodeMap[node.id];
        const parentNode = nodeMap[node.pId];
        if (parentNode) {
          parentNode.children.push(currentNode);
        } else {
          tree.push(currentNode);
        }
      });
      return tree;
    },

    // 获取区划树
    getRegionTree() {
      let query = {
        segmentType: "IsAuto",
        segmentTypeDrink: "filter",
      };
      getRegionTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
        }
      });
    },

    // 获取河流树
    getRiverTree() {
      let query = {
        segmentType: "IsAuto",
        segmentTypeDrink: "filter",
      };
      getRiverSegmentTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
        }
      });
    },

    // 设置所有节点为选中状态
    setAllChecked() {
      // 使用el-tree的setCheckedKeys方法全选
      this.$refs.tree.setCheckedKeys(this.allNodeIds);
      // 触发一次check事件，同步父组件状态
      this.handleCheck(this.$refs.tree.getCheckedNodes(), {
        checkedKeys: this.allNodeIds,
      });
    },

    // 点击节点事件
    handleNodeClick(data) {
      // 保持原逻辑
    },

    // 节点勾选状态变化事件
    handleCheckChange(data, checked) {
      // 保持原逻辑
    },

    // 节点勾选事件（同步给父组件）
    handleCheck(selection, checkedKeys) {
      const ids = checkedKeys.checkedKeys?.join(",") || "";
      this.$emit("node-click", ids);
    },
  },
};
</script>

<style></style>
